import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import User from '@/views/User'
import Search from '@/views/Search'
import SearchResult from '@/views/Search/SearchResult'
import ArticleDetail from '@/views/ArticleDetail'
import UserEditor from '@/views/User/UserEdit'
import Chat from '@/views/Chat'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home'

  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search_result/:keywords',
    component: SearchResult
  },
  {
    path: '/article_detail',
    component: ArticleDetail
  },

  {
    path: '/chat',
    component: Chat
  },
  {
    path: '/user_editor',
    component: UserEditor
  },
  {
    path: '/layout',
    name: 'layout',
    component: Layout,
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        name: 'home',
        component: Home,
        meta:{isRecord:true,top:0}
      }, {
        path: 'user',
        name: 'user',
        component: User
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

import {getToken} from '@/utils/token'
router.beforeEach((to,from,next)=>{
    // 如果当前的路由的元信息中，isRecord 的值为 true
    if (to.meta.isRecord) {
      setTimeout(() => {
        // 则把元信息中的 top 值设为滚动条纵向滚动的位置
        window.scrollTo(0, to.meta.top)
      }, 0)
    }
  // 如果登陆了就不让你回去登录页
  if(getToken()?.length>0&&to.path==='/login'){
    next('/layout/home')
  }else{
    next()
  }
})

export default router
